package com.zn.interceptor;

import com.github.pagehelper.dialect.ReplaceSql;
import com.zn.common.constants.Constants;
import com.zn.common.exception.MyException;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xyl
 * @create 2020/7/1 10:20
 * @desc 权限拦截
 **/
@Log4j2
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        response.setCharacterEncoding("UTF-8");
        //根据登录时 存储的sessionId判断用户是否存在 , 存储的是用户权限 1-普通用户  2-管理员
        if(request.getRequestURI().contains("export_report")){
            return true;
        }
        Integer role = (Integer) request.getSession().getAttribute(request.getSession().getId());
        if (role == null) {
            throw new MyException(702, "请先登录!");
        }
        String[] split = request.getRequestURI().split("/");
        if(role == Constants.ROLE_ORDINARY_USER){  //普通用户
            if("admin".equals(split[1])){
                throw new MyException(702, "无此权限!");
            }else{
                return true;
            }
        }
        if(role == Constants.ROLE_SYSTEM_BOSS){     //超级系统管理员 , 随便操作
            return true;
        }
        if(role == Constants.ROLE_SYSTEM_TEST){     //测试员
            return true;
        }
        if(role == Constants.ROLE_VERIFY){   //审核员
            //判断链接
            return true;
        }
        if(role == Constants.ROLE_AUDITOR){  //审批员
            //判断链接
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
    }
}
